package com.googlecode.lohr.parser.combinators.matcher.common;


import java.util.Arrays;

import com.googlecode.lohr.parser.combinators.MatchResults;
import com.googlecode.lohr.parser.combinators.matcher.MatchContext;
import com.googlecode.lohr.parser.combinators.matcher.Matcher;
import com.googlecode.lohr.parser.combinators.node.AbstractNode;
import com.googlecode.lohr.parser.combinators.node.StringNode;

/**
 * Matches everything from a beginning marker to an ending marker.
 * Markers may NOT be nested. 
 *
 * @author Ted Stockwell
 */
public class SimpleBlockMatcher extends Matcher
{
	String _beginMarker;
	String _endMarker;
	
	public SimpleBlockMatcher(String beginMarker, String endMarker) {
		_beginMarker= beginMarker;
		_endMarker= endMarker;		
	}
	
	@Override
	public MatchResults match(MatchContext ctx, int start) 
	{
		final String input= ctx.getInput();
		if (input.startsWith(_beginMarker, start)) {
			int i= input.indexOf(_endMarker, start+_beginMarker.length());
			if (0 <= i) {
				int e= i+_endMarker.length(); 
				StringNode node= new StringNode(this, start, e, input.substring(start, e));
				return new MatchResults(Arrays.<AbstractNode>asList(node));
			}
			return new MatchResults("Expected end of "+getLabel()+".", input.length());
		}
		return new MatchResults("Expected "+getLabel()+".", start);
	}
	
	@Override
	public String getLabel()
	{
		return "simple block {beginMarker= "+_beginMarker+"; endMarker="+_endMarker+"}";
	}
}
